<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'

import {
  useMessage,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NPopconfirm,
  NTreeSelect,
  NTag,
  NSwitch,
  NFlex,
  NAvatar,
  NSelect,
  NImage,
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import { getToken } from '@/utils'
import { renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'

defineOptions({ name: '报销项目配置' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '报销项目配置',
  initForm: {},
  doCreate: api.createBaoXiaoXm,
  doUpdate: api.updateBaoXiaoXm,
  doDelete: api.deleteBaoXiaoXm,
  refresh: () => $table.value?.handlerefresh(),
})
const isDisabled = ref(false)
const data = reactive({})

onMounted(() => {
  $table.value?.handleSearch()
})

async function addDepts() {
  isDisabled.value = false
  handleAdd()
}

// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.publishing = true
  row.state = row.state === false
  row.publishing = false
  try {
    await api.updateBaoXiaoXm(row)
    $message?.success(row.state ? '已启用' : '已禁用')
    $table.value?.handlerefresh()
  } catch (err) {
    // 有异常恢复原来的状态
    row.state = row.state === false
  } finally {
    row.publishing = false
  }
}

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '报销项目名称',
    key: 'name',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },

  {
    title: '状态',
    key: 'state',
    width: '100',
    align: 'center',
    fixed: 'right',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.state,
        loading: !!row.publishing,
        checkedValue: true,
        uncheckedValue: false,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
  {
    title: '创建时间',
    key: 'created_at',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
  },
  {
    title: '操作',
    key: 'actions',
    width: 'auto',
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                handleEdit(row)
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          [[vPermission, 'post/api/baoxiao/baoxiao_xm/update']]
        ),
        h(
            NPopconfirm,
            {
              onPositiveClick: () => handleDelete({data_id: row.id}, false),
              onNegativeClick: () => {
              },
            },
            {
              trigger: () =>
                  withDirectives(
                      h(
                          NButton,
                          {
                            size: 'small',
                            type: 'error',
                          },
                          {
                            default: () => '删除',
                            icon: renderIcon('material-symbols:delete-outline', {size: 16}),
                          }
                      ),
                      [[vPermission, 'delete/api/baoxiao/baoxiao_xm/delete']]
                  ),
              default: () => h('div', {}, '确定删除该数据吗?'),
            }
        ),
      ]
    },
  },
]
const validateAddUser = {
  name: [
    {
      required: true,
      message: '请输入报销项目名称',
      trigger: ['input', 'blur', 'change'],
    },
  ],
}
</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="报销项目配置">
    <template #action>
      <div>
        <NButton
          v-permission="'post/api/baoxiao/baoxiao_xm/create'"
          class="float-right mr-15"
          type="primary"
          @click="addDepts"
        >
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />
          新建项目
        </NButton>
      </div>
    </template>
    <!-- 表格 -->
    <CrudTable
      ref="$table"
      v-model:query-items="queryItems"
      :columns="columns"
      :get-data="api.getBaoXiaoXm"
    >
      <template #queryBar>
        <QueryBarItem label="报销项目名称" :label-width="120">
          <NInput
            v-model:value="queryItems.name"
            clearable
            type="text"
            placeholder="请输入名称"
            @keypress.enter="$table?.handleSearch()"
          />
        </QueryBarItem>
      </template>
    </CrudTable>

    <!-- 新增/编辑 弹窗 -->
    <CrudModal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :loading="modalLoading"
      @save="handleSave"
    >
      <NForm
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
        :rules="validateAddUser"
      >
        <NFormItem label="项目名称" path="name">
          <NInput v-model:value="modalForm.name" clearable placeholder="请输入项目名称" />
        </NFormItem>

      </NForm>
    </CrudModal>
  </CommonPage>
</template>
